package com.sigmatrix.h5.components;

import java.util.List;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Component;

import com.alibaba.fastjson.JSONObject;
import com.sigmatrix.h5.entity.Enterprise;
import com.sigmatrix.h5.exception.MessageException;
import com.sigmatrix.h5.feign.CoinClient;
import com.sigmatrix.h5.feign.FranchisersClient;
import com.sigmatrix.h5.feign.SSOClient;
import com.sigmatrix.h5.feign.SequenceClient;
import com.sigmatrix.h5.feign.SmsClient;
import com.sigmatrix.h5.feign.WechatClient;
import com.sigmatrix.h5.feign.WechatRedRacketClient;
import com.sigmatrix.h5.feign.args.InStorageParam;
import com.sigmatrix.h5.feign.args.IsvTokenParam;
import com.sigmatrix.h5.feign.args.SequenceParam;
import com.sigmatrix.h5.feign.args.SmsRequest;
import com.sigmatrix.h5.feign.args.SynDealer;
import com.sigmatrix.h5.feign.args.WechatRedPacketDto;
import com.sigmatrix.h5.feign.mode.CoinDto;
import com.sigmatrix.h5.feign.mode.FranchiserResponse;
import com.sigmatrix.h5.feign.mode.IsvToken;
import com.sigmatrix.h5.feign.mode.SequenceResponse;
import com.sigmatrix.h5.feign.mode.SmsResponse;
import com.sigmatrix.h5.feign.mode.WechatAuthorizerConfig;
import com.sigmatrix.h5.feign.mode.WechatRedPacketSendingResponse;
import com.sigmatrix.h5.response.Response;
import com.sigmatrix.h5.service.InStorageService;
import com.sigmatrix.h5.utils.Assert;
import com.sigmatrix.h5.utils.CommonUtils;
import com.sigmatrix.h5.utils.Cons;
import com.sigmatrix.h5.utils.JacksonUtil;
import com.sigmatrix.h5.web.vo.InStorageUpLoad;

import so.sao.sms.dto.api.ResponseVO;
import so.sao.sms.dto.api.SmsSendRequestDTO;
import so.sao.sms.dto.api.SmsSendResponseDTO;
import so.sao.sms.feign.client.SendClient;

/**
 * 
 *@ClassName: FeignManager
 *@Description: 微服务管理工具
 *@author MH
 *@date 2017年11月13日 下午4:33:53
 */
@Component
public class FeignManager {
	private static Logger logger = LoggerFactory.getLogger(FeignManager.class);
	@Autowired
	private FranchisersClient franchisersClient;
	
	@Autowired
	private SequenceClient sequenceClient;
	
	@Autowired
	private SSOClient ssoClient;
	
	@Autowired
	private SmsClient smsClient;
	
	@Autowired
	private SendClient sendClient;
	
	@Autowired
	private WechatClient wechatClient;
	
	@Autowired
	private CoinClient coinClient;
	
	@Autowired
	private WechatRedRacketClient wechatRedRacketClient;
	
//	@Autowired
//	private InStorageClient inStorageClient;
	
//	/**入库业务层接口*/
//	@Autowired
//	private transient InStorageService inStorageService;
	
	/**
	 * 根据经销商推广码获取企业
	 * @param promotionCode
	 * @return Enterprise
	 */
	public Enterprise getEnterpriseBy(String promotionCode){
		logger.info(String.format("基础数据获取企业参数：%s", promotionCode));
		Enterprise enterprise = franchisersClient.getEnterpriseBy(promotionCode);
		logger.info(String.format("基础数据获取企业返回结果：%s", JSONObject.toJSONString(enterprise)));
		return enterprise;
	}
	/**
	 * 
	 *@Title: registDealer
	 *@Description: 基础数据同步
	 *@return FranchiserResponse
	 *@author MH
	 *@date 2017年11月13日 下午4:42:18
	 *@param dealer
	 *@return
	 */
	public FranchiserResponse registDealer(SynDealer dealer){
		logger.info(String.format("基础数据同步经销商参数：%s", JSONObject.toJSONString(dealer)));
		FranchiserResponse response = franchisersClient.regist(dealer);
		logger.info(String.format("基础数据同步经销商返回结果：%s", JSONObject.toJSONString(response)));
		Assert.notNull(response, "基础数据同步返回结果为空");
		return response;
	}
	
	/**
	 * 
	 *@Title: sequence
	 *@Description: 获取序列号
	 *@return Long
	 *@author MH
	 *@date 2017年11月14日 下午5:49:55
	 *@param moduleCode
	 *@param otherPart
	 *@return
	 */
	public Long sequence(String enterpriseCode,String moduleCode,String otherPart){
		logger.info(String.format("获取sequence微服务参数，moduleCode：%s;otherPart:%s", moduleCode,otherPart));
		SequenceParam param = new SequenceParam();
		param.setModuleCode(moduleCode);
		param.setOtherPart(otherPart);
		param.setEnterpriseCode(enterpriseCode);
		SequenceResponse sequence = sequenceClient.sequence(param);
		logger.info(String.format("获取sequence微服务返回结果：%s", JSONObject.toJSONString(sequence)));
		Assert.notNull(sequence, "sequence微服务获取结果失败");
		if(Integer.valueOf(1000).equals(sequence.getCode()))
		return sequence.getData();
		return null;
	}
	/**
	 * 
	 *@Title: isvToken
	 *@Description: 获取ISV access_token
	 *@return IsvToken
	 *@author MH
	 *@date 2018年1月8日 下午3:26:34
	 *@param userName
	 *@param password
	 *@return
	 */
	public IsvToken isvToken(String userName,String password){
		IsvTokenParam vo = new IsvTokenParam();
		vo.setClientName(userName);
		vo.setClientPassword(password);
		logger.info(String.format("短信获取token参数：%s", JSONObject.toJSONString(vo)));
		IsvToken token = ssoClient.getIsvToken(vo);
		logger.info(String.format("短信获取token结果：%s", JSONObject.toJSONString(token)));
		return token;
	}
	
	/**
	 * 
	 *@Title: refreshIsvToken
	 *@Description: 刷新token
	 *@return IsvToken
	 *@author MH
	 *@date 2017年12月14日 上午9:39:39
	 *@param token
	 *@return
	 */
	public IsvToken refreshIsvToken(String token){
		logger.info(String.format("刷新短信token参数：{token:%s}", token));
		IsvToken isvToken = ssoClient.refreshIsvToken(token);
		logger.info(String.format("短信获取token结果：%s", JSONObject.toJSONString(isvToken)));
		return isvToken;
	}
	
	/**
	 * 
	 *@Title: sendMessage
	 *@Description: 发短信
	 *@return SmsResponse
	 *@author MH
	 *@date 2018年1月8日 下午3:31:12
	 *@param request
	 *@param accessToken
	 *@param eseCode
	 *@return
	 */
	public SmsResponse sendMessage(SmsRequest request,String accessToken,String eseCode){
		logger.info(String.format("发送短信参数：{accessToken:%s,componyCode:%s,smsRequest:%s}",accessToken,eseCode,JSONObject.toJSONString(request)));
		SmsResponse response = smsClient.sendShortMessage(request, "Bearer"+accessToken, eseCode);
		logger.info(String.format("发送短信结果：%s",JSONObject.toJSONString(response)));
		return response;
	}
	
	/**
	 *	通过api接口发送短信
	 * 
	 * @param request
	 * @param eseCode
	 * @return
	 */
	public SmsResponse sendMessageThroughApi(SmsRequest request,String eseCode){
		logger.info(String.format("发送短信参数：{componyCode:%s,smsRequest:%s}",eseCode,JSONObject.toJSONString(request)));
		SmsResponse response = smsClient.sendThroughApi(request, eseCode);
		logger.info(String.format("发送短信结果：%s",JSONObject.toJSONString(response)));
		return response;
	}
	
	/**
	 * 
	 *@Title: getAppId
	 *@Description: 获取appId
	 *@return WechatAuthorizerConfig
	 *@author MH
	 *@date 2017年10月16日 下午5:18:24
	 *@param eseId
	 *@return
	 */
	public WechatAuthorizerConfig getAppId(Long eseId){
		logger.info(String.format("微服务获取appId参数：%s",eseId));
		List<WechatAuthorizerConfig> list = wechatClient.getAppIds(eseId);
		Assert.notNull(list, "获取appId失败");
		logger.info(String.format("微服务获取appId结果：%s",JSONObject.toJSONString(list)));
		return list.get(0);
	}
	
	/**
	 * 查询红包参数
	 *@Title: findCoin
	 *@Description: 
	 *@return CoinDto
	 *@author MH
	 *@date 2017年8月25日 下午8:27:09
	 *@param basicModuleEnterpriseId
	 *@return
	 */
	public CoinDto findCoin(Integer basicModuleEnterpriseId){
		try{
			logger.info("获取红包参数："+basicModuleEnterpriseId);
			CoinDto coinDto = coinClient.get(basicModuleEnterpriseId);
			logger.info("红包参数结果："+JSONObject.toJSONString(coinDto));
			return coinDto;
		}catch(Exception e){
			logger.error("查询红包参数失败，基础数据企业ID："+basicModuleEnterpriseId);
			e.printStackTrace();
		}
		return null;
	}
	
	/**
	 * 发微信红包
	 *@Title: sendRedPacket
	 *@Description: 
	 *@return WechatRedPacketSendingResponse
	 *@author MH
	 *@date 2017年8月25日 下午8:41:49
	 *@param wechatRedPacketDto
	 *@return
	 */
	public WechatRedPacketSendingResponse sendRedPacket(WechatRedPacketDto wechatRedPacketDto){
		try{
			logger.info("发送红包参数："+JSONObject.toJSONString(wechatRedPacketDto));
			ResponseEntity<WechatRedPacketSendingResponse> response = wechatRedRacketClient.redPacket(wechatRedPacketDto);
			if(CommonUtils.isNotEmpty(response)){
				logger.info("发送红包返回结果："+JSONObject.toJSONString(response.getBody()));
				return response.getBody();
			}
		}catch(Exception e){
			e.printStackTrace();
		}
		return null;
	}
	
	
	
	public ResponseVO<SmsSendResponseDTO> sendMessage(SmsSendRequestDTO smsReqDto){
		logger.info("发送短信参数：{}",JacksonUtil.write2JsonString(smsReqDto));
		ResponseVO<SmsSendResponseDTO> response = sendClient.send(smsReqDto);
		logger.info("发送短信结果：{}",response==null?"null":JacksonUtil.write2JsonString(response));
		return response;
	}
//	/**
//	 * 
//	 *@Title: updateInStorageCount
//	 *@Description: 层级返利扫码以后修改库存
//	 *@return void
//	 *@author MH
//	 *@date 2017年12月20日 下午3:45:52
//	 *@param dealerId
//	 *@param productId
//	 *@param tag
//	 *@param userId
//	 *@param qrCode
//	 */
//	public void updateInStorageCount(String dealerCode,String parentCode, String productCode, Short tag, Integer userId, String qrCode){
//		InStorageUpLoad inStorageUpLoad = InStorageUpLoad.build(dealerCode,parentCode, productCode, tag, userId, qrCode);
//		InStorageParam build = InStorageParam.build(dealerCode,parentCode, productCode, tag, userId, qrCode);
//		logger.info(String.format("层级返利修改库存参数：%s", JSONObject.toJSONString(build)));
//		Response result = null;
//		try{
//			result = inStorageService.receiptInStorage(inStorageUpLoad);
//		}catch(Exception e){
//			logger.error("修改库存失败", e);
//			throw new MessageException("修改库存失败,请联系管理员");
//		}
//		logger.info(String.format("层级返利修改库存返回结果：%s", JSONObject.toJSONString(result)));
//		if(Cons.RESPONSE_CODE_SUCCESS != result.getCode())throw new MessageException(result.getMessage());
//	}
}
